package com.unlcn.ils.sales.api.rest;

import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.QiniuUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by houjianhui on 2017/8/14.
 */
@Controller
@RequestMapping(value = "/api/qiniu", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "/qiniu", description = "七牛工具类")
public class QiniuRest {

    private static final Logger LOGGER = LoggerFactory.getLogger(QiniuRest.class);

    /**
     * 获取上传凭证
     *
     * @return
     */
    @RequestMapping(value = "/uploadToken", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取上传凭证", notes = "获取上传凭证", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultDTO<Object> generateSimpleUploadToken() {
        ResultDTO<Object> result = new ResultDTO<>(true, null, "获取成功");
        try {
            result.setData(QiniuUtil.generateSimpleUploadToken());
        } catch (Exception e) {
            LOGGER.error("QiniuRest.generateSimpleUploadToken error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 获取下载图片接口
     *
     * @param key 图片KEY
     * @return
     */
    @RequestMapping(value = "/downloadUrl", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取下载图片链接", notes = "获取下载图片链接", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultDTO<Object> generateDownloadURL(String key) {
        ResultDTO<Object> result = new ResultDTO<>(true, null, "获取下载链接成功");
        try {
            result.setData(QiniuUtil.generateDownloadURL(key, ""));
        } catch (Exception e) {
            LOGGER.error("QiniuRest.generateDownloadURL error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }
}
